from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView, RetrieveAPIView

from activity.activityserializer import GatheringSerializer, GatheringDetailsSerializer
from activity.models import Gathering
from activity.pages import PageNum


# 活动列表
class ActivityListView(ListAPIView):
    queryset = Gathering.objects.all()
    serializer_class = GatheringSerializer
    pagination_class = PageNum


# 活动详情
class ActivityRetrieveView(RetrieveAPIView):
    queryset = Gathering.objects.all()
    serializer_class = GatheringDetailsSerializer
    lookup_field = 'id'


# 报名活动
class ActivityGatheringView(RetrieveAPIView):
    def post(self,request,id):
        gathering=Gathering.objects.get(id=id)
        gathering_users =gathering.users.all()
        user=request.user
        if user in gathering_users:
            gathering.users.remove(request.user)
            gathering.save()
            return JsonResponse({ 'success':'true','message': '已取消报名'})
        else:
            gathering.users.add(request.user)
            gathering.save()
            return JsonResponse({'success':'true', 'message': '报名成功'})


